
<template>
  <div>

    <achieve-sum v-if="active===0||active===99" :tabs="tablist"></achieve-sum>

<!--    表单类型的1~6用下面的代码  // 学术论文 a1 学术著作 a2 学术专利 a3 鉴定成果 a4 获奖成果 a5 软件著作 a6-->
    <div v-else>
    <MenuPage
        :selection.sync="selectGroups"
        :columns="columns"
        :data="achieveData"
        :total="achieveCount"
        :page.sync="queryInfo.pageIndex"
        :size.sync="queryInfo.pageSize"
        :loading="loading"
        @queryFun="getLists">

      <template slot="title">
        <div class="class-title-wrap" style="min-width: 700px;">

          <div class="class-title" style="margin-right: 20px;">
            <div class="class-title-all" :class="{'active':active===99}" @click="clickClassText(99)">科研数据</div>
          </div>

          <div class="class-title" v-for="(tab,idx) in tablist" :key="idx" style="margin-right: 20px;">
            <div class="class-title-all" :class="{'active':active===idx}" @click="clickClassText(idx)">{{tab}}</div>
          </div>
        </div>
      </template>
      <template slot="search">
			  <span style='margin-right: 10px;' class="read">

            <Poptip
                        v-if="selectGroups && selectGroups.length> 0"
                        confirm
                        :title="'确定删除选中的'+tablist[active]+'?'"
                        @on-ok="deleteGroups"
                        @on-cancel="">
                <Button ghost style="height: 32px;margin-left: 15px;" type="error" v-if="selectGroups.length != 0">批量删除</Button>
            </Poptip>
            <Button ghost style="height: 32px;margin-left: 15px;" type="error" @click="isDdeleteGroups" v-else>批量删除</Button>
				<Button type="primary" ghost icon="md-add" @click="newInfo" class="ml10">创建{{ tablist[active]}}</Button>
				</span>

        <div v-for="(qitem,idx) in queryforms" :key="idx">
          <Select filterable v-model="query[qitem.key]" :placeholder="qitem.label" v-if="qitem.type==='select'" style="width: 150px;" filterable clearable
                  class="query-item">
            <Option :value='op.value' v-for="(op,i) in qitem.options" v-if="qitem.options && qitem.options.length>0" :key="i">{{op.label}}</Option>
          </Select>

          <template v-if="qitem.type==='selectinput'">
            <AutoComplete
                style="width: 180px"
                v-model.trim="query[qitem.key]"
                :data="qitem.data"
                :placeholder="qitem.label"  />
          </template>

          <Select filterable v-model.trim="query[qitem.key]" :placeholder="qitem.label" filterable clearable v-if="qitem.type==='year'" style="width: 150px">
            <Option :value='year+""' v-for="(year,i) in yearlist"  :key="year+''">{{year}}</Option>
          </Select>

          <Input :placeholder="qitem.label" v-if="qitem.type==='input'" style="width: 180px"
                 v-model.trim="query[qitem.key]" class="query-item" clearable />
        </div>
      </template>
    </MenuPage>
    <achieve-edit ref="editform" :ainfo="ainfo" :close="closeInfo" :tas="tablist"/>
    </div>
  </div>
</template>

<script>
import {
  mapActions,
  mapState
} from 'vuex'
//import CommonPage from '@/components/common/page/page.vue'
import achieveSum from "./components/achieveSum.vue";

import {optionlist,configmap,tablist} from "./achConfig"
import {debounce} from "../../libs/utils";
import achieveEdit from "./components/achieveEdit.vue";
import {getDirectionForSelect, getDirectionType,getList,getAllProjects} from "../../api/achievements";


export default {
  name: 'achievements',
  props: ['type'],
  components:{achieveEdit,achieveSum},
  data() {
    return {
      // 学术论文 a1 学术著作 a2 学术专利 a3 鉴定成果 a4 获奖成果 a5 软件著作 a6
      tablist:tablist,
      dictlist:['zzlb','cbsjb','xmly'],
      ainfo:{},
      methodlist:[],
      yearlist:[],
      active:1,
      modal: false,
      curNotice: {},
      contentHei: 'auto',
     // testc:columnsmap['a'+thia.active]||columnsmap.a1,
      loading:true,
      columns:[],
      achieveData: [],
      achieveCount: 0,
      selectGroups:[],
      queryforms:[],
      query:this.$route.params||{},
      queryInfo: {
        pageIndex: 1,
        pageSize: 20
      }
    }
  },
  watch: {
    $route: { //路由修改后init 页面
      handler: function(route) {
        if(this.$route.query.page!==this.active) {
          this.init()
          this.getProjects()
        }

      },
      deep: true
    },
    query: { //路由修改后init 页面
      handler: function(newv,oldv) {
        this.changeQuery()

      },
      deep: true
    }
  },

  created() {



  },
  filters: {

  },
  computed: {

    colomnsOpera(){
      if(!(this.active>0 && this.active<10)) return []
      let title = this.tablist[this.active].substring(2,4)
      return [{
        title: '操作',
        fixed:'right',
        width:180,
        key: 'action',
        opList:[
          {
            txt:'查看'+title,
            type:'download',
            disabled:(data,e) => {
              if(data.fileinfo && data.fileinfo[0] && data.fileinfo[0].fileName){
                let fname = data.fileinfo[0].fileName
                if(fname.endsWith('.pdf') || fname.endsWith('.doc')|| fname.endsWith('.docx')){
                  return false
                }
              }
              return true
            },
            show:(data,e) => {
              if(data.fileinfo && data.fileinfo[0] && data.fileinfo[0].fileName){
                let fname = data.fileinfo[0].fileName
                if(fname.endsWith('.zip') || fname.endsWith('.rar')){ // 压缩文件查看的是下载 按钮
                  return false
                }
              }
              return true
            },
            on:{
              click:(data,e) => {
                this.preview(data.fileinfo[0])
              }
            }
          },
          {
            txt:'下载'+title,
            type:'download',
            show:(data,e) => {
              if(data.fileinfo && data.fileinfo[0] && data.fileinfo[0].fileName){
                let fname = data.fileinfo[0].fileName
                if(fname.endsWith('.zip') || fname.endsWith('.rar')){
                  return true
                }
              }
              return false
            },
            on:{
              click:(data,e) => {
                this.downloadFile(data.fileinfo[0])
              }
            }
          },
          {
            txt:'编辑',
            type:'check',
            show:(data,e) => {
              return true
            },
            on:{
              click:(data,e) => {
                this.update(data)
              }
            }
          },
          {
            txt: '删除',
            tooltip: true,
            type: 'delete',
            title: `确定要删除这条${title}吗？`,
            show:(data,e) => {
              return true
            },
            on: {
              click: (data,e) => {
                this.delete(data)
              }
            }
          }
        ]
      }]
    }
  },
  mounted() {

    this.initdict()
    this.getNeeddict()
    this.getProjects()//所属项目  下拉框列表信息
    this.init();




  },

  beforeDestroy() {
    sessionStorage.removeItem('achievedict'); // 删除字典的内容下一次重新获取
  },
  methods: {
    getProjects(){
      getAllProjects().then(res => {
        let data = res.data;
        if(data.code == 1) {

          let list = data.data||[]
          let ssxmdicts =  list.map(item=>{
            return {label:item.name,value:item.id}
          })


          let adict = sessionStorage.getItem('achievedict');  // 先取缓存的数据
          let dict = {}
          if(adict){
            dict =  JSON.parse(adict)
          }
          dict['ssxm'] = ssxmdicts

          sessionStorage.setItem('achievedict',JSON.stringify(dict));
        }
      })
    },
    initdict(){
      let adict = sessionStorage.getItem('achievedict');  // 先取缓存的数据
      let dict = {}
      if(adict){
        dict =  JSON.parse(adict)
      }

      dict['unknown'] = [{label:'未知',value:'未知'}]
      dict['hjjb'] = [{label:'国际级',value:'国际级'},{label:'国家级',value:'国家级'},{label:'部级',value:'部级'},{label:'省级',value:'省级'}] // 获奖级别
      dict['jldj'] = [{label:'特等奖',value:'特等奖'},{label:'一等奖',value:'一等奖'},{label:'二等奖',value:'二等奖'},{label:'三等奖',value:'三等奖'}] // 获奖等级
      dict['jllb'] = [{label:'国家最高科学技术奖',value:'国家最高科学技术奖'},{label:'国家自然科学奖',value:'国家自然科学奖'},{label:'国家发明奖',value:'国家发明奖'}] // 奖励类别

      dict['jdjl'] = [//鉴定结论
        {label:'国家级国际先进水平',value:'国家级国际先进水平'},
        {label:'国家级国内先进水平',value:'国家级国内先进水平'},
        {label:'国家级国际领先水平',value:'国家级国际领先水平'},
        {label:'国家级国内领先水平',value:'国家级国内领先水平'}
      ] // 奖励类别

      //
      dict['lwfbdj'] = [//鉴定结论
        {label:'A类权威核心刊物论文',value:'A类权威核心刊物论文'},
        {label:'B类重要核心刊物论文',value:'B类重要核心刊物论文'},
        {label:'C类一般核心刊物论文',value:'C类一般核心刊物论文'},
        {label:'D类一般公开刊物论文',value:'D类一般公开刊物论文'},
        {label:'E类受限公开刊物论文',value:'E类受限公开刊物论文'},
      ]

      dict['rjzzlb'] = [//软件著作类别
        {label:'界面设计',value:'界面设计'},
        {label:'计算机程序',value:'计算机程序'},
        {label:'程序设计文档',value:'程序设计文档'},
        {label:'网页设计',value:'网页设计'},
        {label:'算法设计',value:'算法设计'},
        {label:'数据库设计',value:'数据库设计'},
      ]

      dict['fbfw'] = [//发表范围
        {label:'国外学术期刊',value:'国外学术期刊'},
        {label:'国内公开发行',value:'国内公开发行'},
        {label:'国内外公开发行',value:'国内外公开发行'},
        {label:'港澳台刊物',value:'港澳台刊物'}
      ]




      dict['jllx'] = [{label:'成果奖',value:'成果奖'},{label:'人才奖',value:'人才奖'}]//奖励类型
      dict['zllx'] = [{label:'发明',value:'发明'},{label:'实用新型',value:'实用新型'}]//专利类型
      dict['wcxs'] = [{label:'独立完成',value:'独立完成'},{label:'与外单位合作',value:'与外单位合作'}] // 论文类型
      dict['lwlx'] = [{label:'期刊论文',value:'期刊论文'},{label:'会议论文',value:'会议论文'}] // 论文类型
      dict['xxsm']= [{label:'第一单位',value:'第一单位'},{label:'非第一单位',value:'非第一单位'}] // 学校书名
      sessionStorage.setItem('achievedict',JSON.stringify(dict));
    },
    async getNeeddict(){ // 获取所需要的字典数据，放到session里面
      for(let i=0;i<this.dictlist.length;i++){
         await getDirectionForSelect(this.dictlist[i])
      }
      this.loading = false
    },
    getTimes(){
      return 'sdfsfsfsd'
    },
    setVisibility(){
      return 'setVisibility'
    },
    init(){
      // 1. 获取当前的page 配置
      this.active = this.$route.query.page===undefined?99:Number(this.$route.query.page)
      let pinfo = configmap['a'+this.active]||configmap.a1
      this.getColums(pinfo)
      this.formatQuery(pinfo.query)
      this.formatMethod(pinfo)


      let curYear = new Date().getFullYear()
      let yearlist = []
      for(let i=0;i<200;i++){
        yearlist.push(curYear-i)
      }
      this.yearlist = yearlist

    },
    getColums(pinfo){

      let columns = pinfo.columns||[] // 2.table的表字段
      let key = 'a'+this.active

      let colomnsOpera = this.colomnsOpera

      this.columns =[...columns,...colomnsOpera]

    },
    async formatQuery(querylist){ // 3.查询表单的数据格式化
      // {label:'论文名称',key:'name',type:'input'},
      querylist = querylist||[]
      let query= {}
      querylist.forEach(item=>{
        let key = item.key
        query[key]=item.value||''
      })
      let paramquery = this.$route.params||{}
      this.query = {
        ...query,
        ...paramquery // 以 参数传来的为主
      }

      let queryforms=[]
      for(let i=0;i<querylist.length;i++){
        let item = querylist[i]
        item.options=item.options||[]
        if(item.dictid){
          let res = await getDirectionForSelect(item.dictid)
          item.options = res || []
          // AutoComplete的data数据
          if(item.type==='selectinput'){
            let autodata = []
            item.options.forEach(item=>{
              if(item && item.label){
                autodata.push(item.label)
              }
            })
            item.data = autodata
          }
        }
        queryforms.push(item)
      }
      this.queryforms = queryforms

    },

    formatMethod(pinfo){ // 4.增删改查调用的接口引入
      let _this = this
      _this.methodlist=[]
      import('@/api/achievements').then(module => { //动态引入的方法
        let methodNames = pinfo.methodName||[]
        methodNames.forEach(methodName=>{
          let method = module[methodName];
          _this.methodlist.push(method);
        })
        _this.getLists()
      }).catch(error => {
        console.error('动态引入API方法失败：', error);
      });
    },



    getLists() {



        let query = this.query
        let queryInfo = this.queryInfo
        let params  ={
          ...query,
          ...queryInfo,
          type:this.$route.query.page===undefined?99:Number(this.$route.query.page)
        }



      getList(params).then(res => {
          let data = res.data;
          if(data.code == 1) {
            let achieveData = data.data.items||[]

            this.achieveData = achieveData.map(item=>{
              let detail = item.detail
              let ddate = {}
              if(detail){
                ddate = JSON.parse(detail)
              }
              let mergedObj = Object.assign({}, ddate, item);// item 的数据为准
              return mergedObj
            })

            this.achieveCount = data.data.total;
          }
        })


    },
    changeQuery:debounce(function(){
      this.queryInfo.pageIndex = 1;
      this.getLists();
    },200),
    change(page) {
      this.queryInfo.pageIndex = page;
      this.getLists();
    },
    typeFilter(type) {
      let types = '事务公告';
      return types;
    },

    deleteGroups(){
      let ids = this.selectGroups.map(item=>{
        return item.id
      })

      this.selectGroups=[]
      this.delete(ids)

    },

    isDdeleteGroups(){
      let ids = this.selectGroups.map(user => user.id).join(',');
      if(ids.length === 0){
        this.$Message.error(`请选择需要删除的${this.tablist[this.active]}！`)
        return
      }
    },
    newInfo() {
      this.ainfo={}
      this.$refs['editform'].isValidate = true
      this.$refs['editform'].modal = true
    },
    closeInfo() {
      this.$refs['editform'].modal = false
      this.ainfo={}
      this.getLists()
    },
    clickClassText(idx){
      let name = this.$route.name
      this.$router.push({name:name,query:{page:idx}})
    },
    cancelModal(){
      this.modal = false;
      this.$emit('showPop', true);
    },
    delete(data){
      debugger
      console.log('delete data',data)
      let ids=data
      if(data.id){
        ids=[data.id]
      }else {

      }

      if(this.methodlist && this.methodlist.length===4){
        this.methodlist[1](ids).then(res => {
          let data = res.data;
          if(data.code == 1) {
            this.$Message.success('删除成功')
            this.getLists()
          }else {
            this.$Message.warning(data.message)
          }
        })
      }
    },
    update(data){
      this.ainfo = data||{}
      this.$refs['editform'].modal = true
    },


    getTypeName(type) {
      let typeList = type.split(',');
      if(typeList.length === 1){
        return this.getNameById(typeList[0],this.allType)
      }else{
        return `${this.getNameById(typeList[0],this.allType)}，${this.getNameById(typeList[1],this.allType)}`;
      }
    },
    preview(file){
      //let fileId = file.id;
      let path = file.path;
      window.open(`/api/minio/filePreview?path=${path}`);

    },
    downloadFile(file){
      let path = file.path
      if(!path){
        this.$Message.warning('文件错误')
        console.error('文件错误',file)
        return
      }
      const msg = this.$Message.loading({
        content: '下载中...',
        duration: 0,
        closable: true
      });
      let href = this.url;
      let a = document.createElement('a');
      document.body.appendChild(a);
      if(this.params){
        let paramsStringArr = [];
        for(let key in this.params){
          if(this.params[key]){
            paramsStringArr.push(`${key}=${this.params[key]}`)
          }
        }
        let paramsStringTxt = paramsStringArr.join('&')
        href = `${href}?${paramsStringTxt}`
      }
      a.href = `/api/minio/download?path=${path}`;
      a.download = ''; //命名下载名称
      a.click(); //点击触发下载
      a.remove();
      setTimeout(msg, 500);
    },


  },
  destroyed() {

  }
}
</script>
<style scoped>
.all-class{
  background-color: var(--card-body-bgcolor);
  border-radius: 10px;
  padding: 30px 0;
}
.class-top{
  display: flex;
  justify-content: space-between;
  padding: 0 30px;
}
.class-title-wrap{
  display: flex;
  justify-content: flex-start;
  align-items: start;
}
.class-title{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.class-title-all{
  font-size: 16px;
  cursor: pointer;
  line-height: 34px;
}
.active{
  color: var(--defulat-color);
  font-size: 22px;
  font-weight: 600;
}
/deep/ .pt-content-top{
  align-items: start !important;
}
.query-item{
  width: 150px;
  text-align: left;
  border-radius: 10px;
}


/* 菜单页 */
/deep/.pt-content-menu {
  background-color: var(--card-body-bgcolor);
  border-radius: 8px;
  height:100%;
  /* height: calc(100% - 60px)!important;
  margin:30px; */
}
/deep/.pt-content-menu > .pt-content-top{
  padding:20px 20px 0;
}
/deep/.pt-content-menu > .pt-content-wrap {
  padding:0 20px 20px;
}
</style>
